/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.node;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;

/*
 * Contains nodes (NodeInfo) that are assigned to this requested node set 
 *   (NodeAllocateSet) which each node is matched with node num, ppn and 
 *   ncpus of the request.
 */
public class NodeAllocateSet {

	private final int reqNum;
	private final Collection<NodeResource> resources; // requested node resources.  Collections is defined here! but may be use practically as one element.
	private final HashSet<NodeInfo> rsvdNodes;

	private NodeAllocateSet(int reqNum, Collection<NodeResource> rscs,
			NodeResource initRsc) {

		this.reqNum = reqNum;
		this.resources = (rscs != null)
			? rscs : new LinkedList<NodeResource>();
		if (initRsc != null) {
			this.resources.add(initRsc);
		}
		this.rsvdNodes = new HashSet<NodeInfo>();

	}

	public NodeAllocateSet(int reqNum, NodeResource resource) {

		this(reqNum, null, resource);

	}

        /*
         *  Why new NodeResource(1,1) is added as the initial resource !!!
         */
	public NodeAllocateSet(int reqNum, Collection<NodeResource> resources) {

		this(reqNum, resources, new NodeResource(1, 1));

	}

	public int getRequestedNum() {

		return reqNum;

	}

	public Collection<NodeResource> getRequestedResources() {

		return resources;

	}

	public boolean isAllocatedEnough() {

		return (rsvdNodes.size() >= reqNum);

	}

	public void addAllocatedNode(NodeInfo node) {

		assert(isAllocatedEnough() == false);
		if (rsvdNodes.contains(node) == false) {
			// duplicate allocation of same node is ignored
			rsvdNodes.add(node);
		} else {
			assert(false);
		}

	}

	public String toString() {

		return "reqnum=" + reqNum + ", allocatedNum=" + rsvdNodes.size()
			+ ", resources=" + resources.toString();

	}

}
